package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInContractDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.util.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住Service业务层处理
 *
 * @author alexis
 * @date 2025-11-01
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return checkInMapper.deleteById(id);
    }

    /**
     * 申请入住
     *
     * @param checkInApplyDto
     */
    @Override
    @Transactional
    public void apply(CheckInApplyDto checkInApplyDto) {
        //1.判断老人是否入住--根据老人身份证号和状态
        LambdaQueryWrapper<Elder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Elder::getIdCardNo, checkInApplyDto.getCheckInElderDto().getIdCardNo())
                .eq(Elder::getStatus, 1);
        Elder elder = elderMapper.selectOne(wrapper);
        if (ObjectUtil.isNotEmpty(elder)) {
            throw new RuntimeException("该老人已入住");
        }

        //2.更新床位信息
        Bed bed = bedMapper.selectBedById(checkInApplyDto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);

        //3.新增或者更新老人信息
        elder = insertOrUpdate(bed, checkInApplyDto.getCheckInElderDto());

        //4.新增签约信息
        String number = "HT" + CodeGenerator.generateContractNumber();
        insertContract(number, elder, checkInApplyDto);

        //5.新增入住信息
        CheckIn checkIn = insertCheckIn(elder, checkInApplyDto);
        //6.新增入住配置信息
        insertCheckInConfig(checkIn, checkInApplyDto);
    }


    //新增入住配置信息
    private void insertCheckInConfig(CheckIn checkIn, CheckInApplyDto checkInApplyDto) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
    }

    //新增入住信息
    private CheckIn insertCheckIn(Elder elder, CheckInApplyDto checkInApplyDto) {
        CheckIn checkIn = new CheckIn();
        //拷贝入住信息
        BeanUtils.copyProperties(checkInApplyDto, checkIn);
        //添加入住信息中的老人相关信息
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setBedNumber(elder.getBedNumber());
        //添加入住配置信息
        checkIn.setNursingLevelName(checkInApplyDto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        //添加家人信息为备注
        checkIn.setRemark(JSON.toJSONString(checkInApplyDto.getElderFamilyDtoList()));
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    //新增签约信息
    private void insertContract(String number, Elder elder, CheckInApplyDto checkInApplyDto) {
        Contract contract = new Contract();
        //拷贝签约信息
        BeanUtils.copyProperties(checkInApplyDto.getCheckInContractDto(), contract);
        //添加签约编号
        contract.setContractNumber(number);
        //添加老人信息
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        //拷贝入住配置中的时间信息
        LocalDateTime startDate = checkInApplyDto.getCheckInConfigDto().getStartDate();
        contract.setStartDate(startDate);
        LocalDateTime endDate = checkInApplyDto.getCheckInConfigDto().getEndDate();
        contract.setEndDate(endDate);
        //状态判断设置
        Integer status = startDate.isBefore(LocalDateTime.now()) ? 1 : 0;
        contract.setStatus(status);
        //新增签约信息
        contractMapper.insert(contract);
    }
    //新增或者更新老人信息
    private Elder insertOrUpdate(Bed bed, CheckInElderDto checkInElderDto) {
        Elder elder = new Elder();
        BeanUtils.copyProperties(checkInElderDto, elder);
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
        elder.setStatus(1);

        //查询老人信息
        LambdaQueryWrapper<Elder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo());
        Elder elderDB = elderMapper.selectOne(wrapper);
        if (ObjectUtil.isEmpty(elderDB)) {
            //如果没有数据则插入
            elderMapper.insert(elder);
        } else {
            //如果有数据则进行更新
            elder.setId(elderDB.getId());
            elderMapper.updateById(elder);
        }
        return elder;
    }

    /**
     * 查询入住详情
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo detail(Long id) {
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        //1.查询入住+入住配置信息
        CheckIn checkIn = checkInMapper.selectById(id);
        LambdaQueryWrapper<CheckInConfig> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(CheckInConfig::getCheckInId, checkIn.getId());
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(wrapper1);
        //复制到详情对象中
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtils.copyProperties(checkInConfig, checkInConfigVo);
        BeanUtils.copyProperties(checkIn, checkInConfigVo);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        //2.查询老人信息
        Elder elder = elderMapper.selectById(checkIn.getElderId());
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        BeanUtils.copyProperties(elder, checkInElderVo);
        checkInElderVo.setAge(IdcardUtil.getAgeByIdCard(elder.getIdCardNo()));
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        //3.家属响应信息
        String remark = checkIn.getRemark();
        List<ElderFamilyVo> elderFamilyVoList = JSON.parseArray(remark, ElderFamilyVo.class);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);

        //4.设置签约办理
        LambdaQueryWrapper<Contract> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(Contract::getElderId, checkIn.getElderId());
        Contract contract = contractMapper.selectOne(wrapper2);
        checkInDetailVo.setContract(contract);
        return checkInDetailVo;
    }
}
